package com.cloud.servicezuul.compoment;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.net.URL;

@Component
public class RouteFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.ROUTE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @SneakyThrows
    @Override
    public Object run() {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String requestURI = request.getRequestURI();

        //将所请求的服务中的method1(服务中可能没有method1这个方法) 映射到 method2
        if (requestURI.contains("/getMessage")){
            String mapping = getMethodMapping(requestURI);
            String serviceId = getServiceId(mapping);
            String methodName = getMethodName(mapping, serviceId);
            //转发到新的请求
            currentContext.put(FilterConstants.SERVICE_ID_KEY,serviceId);
            currentContext.put(FilterConstants.REQUEST_URI_KEY,methodName);
        }
        //将不存在的服务，映射到存在的服务上
        if (requestURI.contains("/service-sms1")){
            currentContext.setRouteHost(new URL("http://localhost:8999/getNewMessage"));
        }

        return null;
    }

    private String getServiceId(String requestUri){
        if (requestUri.startsWith("/")){
            return requestUri.substring(1).split("/")[0];
        }
        return requestUri;
    }

    private String getMethodName(String requestUri,String serviceId){
       return requestUri.substring(serviceId.length() +1);
    }

    private String getMethodMapping(String requestUri){
        //模拟一下取到对应的映射
        return "/service-sms/getNewMessage";
    }
}
